package com.xwdeshj.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xwdeshj.entity.XwBanner;
import com.xwdeshj.repository.XwBannerRepository;
import com.xwdeshj.service.XwBannerService;
import com.xwdeshj.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Created by BKWJA on 2018/12/20.
 */
@Slf4j
@Service("xwBannerService")
public class XwBannerServiceImpl implements XwBannerService {

    @Autowired
    private XwBannerRepository xwBannerRepository;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private Sid sid;

    @Override
    public JSONObject getbannerlist(Integer pageindex, Integer pagesize, String starttime,
                                    String endtime, String sortfild, String sortway) {
        JSONObject result = new JSONObject();
        String sql = "select banner_Id,banner_encryptId,banner_img,banner_desc,banner_createtime,banner_updatetime from xw_banner ";
        StringBuffer sb = new StringBuffer();
        sb.append(" 1=1 ");
        if(!starttime.equals("")){
            starttime += " 00.00.01";
            endtime += " 23.59.59";
            sb.append(" and banner_createtime >= '"+starttime+"' and banner_createtime <= '"+ endtime + "' ");
        }
        //排序
        if (!sortfild.equals("")){
            sb.append(" order by "+sortfild+" " +sortway + " ");
        }
        try {
            sql = sql + " where " +sb.toString() + " limit "+ (pageindex-1)*pagesize + "," + pagesize;
            //分页SQL
            String sql2 = "select count(*) from xw_banner where " + sb.toString();
            SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
            SqlRowSet rs2 = jdbcTemplate.queryForRowSet(sql2);
            result.put("status",0);
            result.put("msg","ok");
            while (rs2.next()){
                Integer count = rs2.getInt(1);
                result.put("recordcount",count);
                if (count%pagesize == 0){
                    result.put("pagecount",count/pagesize);
                }else {
                    result.put("pagecount",count/pagesize + 1);
                }
            }
            JSONArray jsonArray = new JSONArray();
            while (rs.next()){
                JSONObject object = new JSONObject();
                object.put("banner_Id",rs.getString("banner_Id"));
                object.put("banner_encryptId",rs.getString("banner_encryptId"));
                object.put("banner_img",(rs.getString("banner_img")==null?"":rs.getString("banner_img")));
                object.put("banner_desc", (rs.getString("banner_desc")==null?"":rs.getString("banner_desc")));
                object.put("banner_updatetime", DateUtil.DateToString(rs.getDate("banner_updatetime")));
                object.put("banner_createtime",DateUtil.DateToString(rs.getDate("banner_createtime")));
                jsonArray.add(object);
            }
            result.put("list",jsonArray);
        }catch (Exception e){
            e.printStackTrace();
            result.put("status",500);
            result.put("msg",e);
        }
        System.out.println("getbannerlist:"+result.toString());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject updatebanner(String banner_encryptId, String banner_img, String banner_desc) {
        JSONObject result = new JSONObject();

        if(banner_encryptId.equals("")){
            XwBanner banner = new XwBanner();
            banner.setBannerEncryptid(sid.nextShort());
            banner.setBannerImg(banner_img);
            banner.setBannerDesc(banner_desc);
            banner.setBannerCreatetime(new Date());
            banner.setBannerUpdatetime(new Date());
            try {
                xwBannerRepository.save(banner);
                result.put("status",0);
                result.put("msg","ok");
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg",e);
            }
        }else {
            XwBanner bannerinfo = xwBannerRepository.findByBannerEncryptid(banner_encryptId);

            if (bannerinfo != null){
                bannerinfo.setBannerImg(banner_img);
                bannerinfo.setBannerDesc(banner_desc);
                bannerinfo.setBannerUpdatetime(new Date());
                try {
                    xwBannerRepository.save(bannerinfo);
                    result.put("status",0);
                    result.put("msg","ok");
                }catch (Exception e){
                    e.printStackTrace();
                    result.put("status",500);
                    result.put("msg",e);
                }
            }else {
                result.put("status",500);
                result.put("msg","该记录不存在！");
            }

        }
        System.out.println("updatebanner:"+result.toString());
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @Modifying
    public JSONObject delbanner(String banner_encryptId) {
        JSONObject result = new JSONObject();
        if(!"".equals(banner_encryptId) && banner_encryptId != null){
            try {
                if(banner_encryptId.indexOf(",") == -1){
                    //单个删除
                    xwBannerRepository.deleteByBannerEncryptid(banner_encryptId);
                }else {
                    //批量删除
                    String[] tids = banner_encryptId.split(",");
                    for (int i = 0; i < tids.length; i++) {
                        xwBannerRepository.deleteByBannerEncryptid(tids[i]);
                    }
                }
                result.put("status",0);
                result.put("msg","ok");
            }catch (Exception e){
                e.printStackTrace();
                result.put("status",500);
                result.put("msg",e);
            }

        }else {
            result.put("status",500);
            result.put("msg","banner_encryptId不能为空！");
        }
        System.out.println("delbanner："+result);
        return result;
    }

    @Override
    public JSONObject getBannerByEncryptId(String banner_encryptId) {
        JSONObject result = new JSONObject();
        String sql = "select banner_Id,banner_encryptId,banner_img,banner_desc from xw_banner ";
        StringBuffer sb = new StringBuffer();
        sb.append(" 1=1 ");
        if(!banner_encryptId.equals("")){
            //批量删除
            String[] tids = banner_encryptId.split(",");
            String temp = "";
            for (int i = 0; i < tids.length; i++) {
                if (i==0){
                    temp = ("'"+tids[i]+"'");
                }else {
                    temp += (",'"+tids[i]+"'");
                }
            }
           sb.append(" and banner_encryptId in ("+temp+") ");
           try {
               sql = sql + " where " +sb.toString();
               SqlRowSet rs = jdbcTemplate.queryForRowSet(sql);
               JSONArray array = new JSONArray();
               while (rs.next()){
                   JSONObject object = new JSONObject();
                   object.put("banner_Id",rs.getString("banner_Id"));
                   object.put("banner_encryptId",rs.getString("banner_encryptId"));
                   object.put("url",(rs.getString("banner_img")==null?"":rs.getString("banner_img")));
                   object.put("title", (rs.getString("banner_desc")==null?"":rs.getString("banner_desc")));
                   array.add(object);
               }
               result.put("list",array);
               result.put("status",0);
               result.put("msg","ok");
           }catch (Exception e){
               e.printStackTrace();
               result.put("status",500);
               result.put("msg",e);
           }
        }
        System.out.println("getBannerByEncryptId:"+result.toString());
        return result;
    }
}
